<template>
  <div class="chat-container">
    <!-- 联系人列表 -->
    <div class="contact-list">
      <el-scrollbar height="520px">
        <el-badge v-for="item in contacts" :offset="[-10,5]" :hidden="item.unreadCount<1" :value="item.unreadCount" :key="item.id" class="badgeMan">
          <template #content="{ value }">
            <div class="custom-content">
              <el-icon>
                <Message />
              </el-icon>
              <span>{{ value }}</span>
            </div>
          </template>
          <el-button :class="item.targetId==currentChat?'activeButton':'unActive'" style="width: 100%;height: 50px" @click="loadChatHistory(item.targetId)">{{item.targetId}}</el-button>
        </el-badge>
      </el-scrollbar>
    </div>

    <!-- 聊天区域 -->
    <div v-if="currentChat" class="chat-area">
      <div class="chat-main">
        <el-icon v-show="loading"><Loading /></el-icon>
        <div v-if="showLoadMore" class="load-more-prompt" @click="loadMoreMessages">
           点击加载更多消息
        </div>
        <div class="message-list" ref="messageListRef" @scroll="handleScroll">
          <div v-for="msg in chatStore.messages" :key="msg.messageId"
               :class="['message-item', msg.senderId==userInfo.userInfo?.userId ? 'right' : 'left']">
            <!-- 文本消息 -->
            <div class="message-bubble">
              {{ msg.content }}
            </div>

            <!-- 图片消息 -->
            <div v-if="msg.attachments?.length" class="media-bubble">
              <div v-for="(file, index) in msg.attachments" :key="index">
                <el-image v-if="['jpg','jpeg','png','gif','image'].includes(file.fileType)"
                          :src="file.fileUrl"
                          fit="cover"
                          class="thumbnail"/>

                <!-- 视频类型 -->
                <video v-else-if="['mp4','webm','ogg'].includes(file.fileType)"
                       controls
                       class="video-preview">
                  <source :src="file.url" :type="`video/${file.fileType}`">
                </video>

                <!-- 其他文件类型 -->
                <div v-else class="file-message">
                  <el-icon class="file-icon"><Document /></el-icon>
                  <div class="file-info">
                    <a :href="file.fileType" download class="file-link">
                      {{ file.fileName }}
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 在输入框上方添加文件预览 -->
      <!-- 消息输入 -->
        <div class="message-input">
          <div style="display:flex;">
            <el-button @click="toggleUploadPanel" :icon="showUploadPanel ? Minus : Plus" circle />
            <el-input v-model="newMessage"
                      type="textarea"
                      :autosize="{ minRows: 1, maxRows: 4 }"
                      placeholder="输入消息..." />
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </div>
        </div>
      </div>
  </div>
    <!-- 右侧预览区域 -->
    <div class="preview-pane" v-if="showUploadPanel">
      <el-upload
        action="http://[2409:8a4c:832:c590::36b]:8081/upload"
        v-model:file-list="fileList"
        :on-success="handleUploadSuccess"
        :before-upload="beforeFileUpload"
        multiple
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      </el-upload>
    </div>
    </div>

</template>

<script setup lang="ts">
import { h, ref, onMounted, nextTick, watch } from 'vue'
import { ElAvatar, ElBadge, ElMessage, type UploadUserFile } from 'element-plus'
import { Warning, Loading,Message,Plus, Minus, UploadFilled, Document } from '@element-plus/icons-vue'
import { useChatStore } from '@/stores/ws';
import { useUserStore } from '@/stores/user.ts';
import { getChatContacts, clearUnreadCount, getChatMessages } from '@/common/net/api';
const page = ref(1);
const pageSize = 20;
const loading = ref(false);
const previewUrl = ref('')
const previewType = ref('')
const fileList = ref<UploadUserFile[]>()
// 新增响应式状态
const showUploadPanel = ref(false)
const isUploading = ref(false)
// 添加消息列表容器引用
const messageListRef = ref<HTMLElement | null>(null)
// 切换上传面板方法
const toggleUploadPanel = () => {
  showUploadPanel.value = !showUploadPanel.value
}
// 数据部分
const chatStore = useChatStore();
const userInfo = useUserStore();
const newMessage = ref('');
const contacts = ref<any[]>([]);
const currentChat = ref<number | null>(null);
// 自动滚动逻辑
const scrollToBottom = () => {
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

const getFileName = (url: string) => {
  return url.split('/').pop()
}
const formatTimestamp = (timestamp: any) => {
  // Handle both array and object timestamp formats
  if (Array.isArray(timestamp)) {
    const [year, month, day, hour, minute] = timestamp;
    return `${year}-${month}-${day} ${hour}:${minute}`;
  }

  // Handle UNIX timestamp format
  if (typeof timestamp === 'number') {
    const date = new Date(timestamp);
    return date.toLocaleString();
  }

  return 'Invalid date';
};
const hasMore = ref(true)
const showLoadMore = ref(false)
const prevScrollInfo = ref({ top: 0, height: 0 })

const handleScroll = (e: Event) => {
  const container = messageListRef.value
  if (!container) return
  if (loading.value) {

    if (container.scrollTop < container.scrollHeight - container.clientHeight) {
      container.scrollTop = container.scrollHeight - container.clientHeight
    }
    return
  }
  // 禁止向上滚动
  // 检测是否滚动到顶部（距顶部20px内）
  showLoadMore.value = container.scrollTop < 5 && !loading.value && hasMore.value
  // if (container.scrollTop < 5 && !loading.value && hasMore.value) {
  //   loadMoreMessages()
  // }
}
const loadMoreMessages = async () => {
  const container = messageListRef.value
  if (!container) return
  try {
    console.log('加载更多')
    loading.value = true
    showLoadMore.value = false
    // 记录当前滚动位置
    prevScrollInfo.value = {
      top: container.scrollTop,
      height: container.scrollHeight
    }
    page.value++;
    const response = await getChatMessages(currentChat.value!, page.value, pageSize);
    if(response.data.data.length<1) {
      ElMessage({
        message: '没有更多消息了',
        type: 'info',
        duration: 3000
      })
      return
    }

    chatStore.updateMessagesMore(response.data.data.reverse());
    // 保持滚动位置
    await nextTick(() => {
      if (container) {
        const heightDiff = container.scrollHeight - prevScrollInfo.value.height
        container.scrollTop = prevScrollInfo.value.top + heightDiff
      }
    })
  } finally {
    loading.value = false;
  }
};
// 获取联系人列表
const fetchContacts = async () => {
  try {
    const response = await getChatContacts();
    contacts.value = response.data.data;
  } catch (error) {
    console.error('获取联系人列表失败:', error);
  }
};
// 文件上传成功处理
const handleUploadSuccess = (response: any, file: File) => {
  const uploadedFile = {
    url: response.data,  // 根据实际接口调整
    name: file.name,
    size: file.size,
    type: file.type
  }
  console.log('文件上传成功:', fileList.value);
}

// 文件上传前校验
const beforeFileUpload = (file: File) => {
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }
  return true
}

// 文件大小格式化
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
// 加载聊天记录
const loadChatHistory = async (targetId: number) => {

  showUploadPanel.value = false
  chatStore.clearMessages()
  chatStore.currentChat = targetId
  currentChat.value = targetId
  try {
    // 清空未读数
    await clearUnreadCount(targetId);
    // 获取聊天记录
    const response = await getChatMessages(targetId);
    chatStore.updateMessages(response.data.data.reverse())
    // 更新联系人未读数
    const contact = contacts.value.find(c => c.id === targetId);
    if (contact) contact.unreadCount = 0;
    scrollToBottom()
  } catch (error) {
    console.error('获取聊天记录失败:', error);
  }
};

// 发送消息
const sendMessage = () => {
  chatStore.sendMessage(newMessage.value, String(currentChat.value),fileList.value);
  fileList.value=[]
  showUploadPanel.value = false
  newMessage.value = '';
  scrollToBottom()
};

// 时间格式化
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString();
};

// 联系人行样式
const getContactRowClass = ({ rowIndex }: any) => ({
  'contact-row': true,
  'active': contacts.value[rowIndex]?.id === currentChat.value
});
watch(
  () => chatStore.isVisible,
  (newVal, oldVal) => {
    console.log('消息列表更新')
    scrollToBottom()
  }
)

// 初始化
onMounted(async () => {
  await userInfo.fetchUserInfo();
  chatStore.initConnection();
  await fetchContacts();
});
</script>

<style scoped lang="scss">
.badgeMan{
  width: 186px;
  margin: 6px auto;
}
.chat-container {
  display: flex;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
}
.custom-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}
.load-more-prompt {
  text-align: center;
  padding: 8px;
  background: #c6c9cd;
  cursor: pointer;
  &:hover {
    background: #e4e7ed;
  }
}
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;  // 新增
}
.preview-pane {
  position: absolute;
  right: -410px;
  border: 1px solid #164dcd;
  width: 400px;
  border-radius: 8px;
  height: 400px;
  border-left: 1px solid #ebeef5;
  padding: 20px;
  background: #f5f7fa;
  .el-image {
    width: 100%;
    height: 100%;
  }
}

.thumbnail {
  width: 200px;
  height: 150px;
  border-radius: 8px;
  cursor: pointer;
}

.file-bubble {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 8px;

  .file-icon {
    font-size: 24px;
    margin-right: 10px;
  }
}

.message-input {
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #ebeef5;
  :deep(.el-textarea__inner) {
    resize: none; // 禁用手动调整大小
    line-height: 1.5;
    padding: 8px 12px;
  }
}
.contact-list {
  width: 200px;
  border-right: 1px solid #c4c7d2;
  background: #e2e2e2;

  h3 {
    padding: 16px;
    margin: 0;
    color: #303133;
    border-bottom: 1px solid #ebeef5;
  }
}
.activeButton{
  background-color: #409eff;
  color: white;
}
.contact-row {
  padding: 12px;
  cursor: pointer;
  transition: background-color 0.3s;

  &:hover {
    background-color: #e4e7ed;
  }

  &.active {
    background-color: #409eff;
    color: white;
  }
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.message-bubble {
  margin: 8px 0;
  padding: 12px;
  border-radius: 8px;
  max-width: 80%;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);

  &.sent {
    margin-left: auto;
    background: #409eff;
    color: white;
  }
}

.message-content {
  word-break: break-word;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.message-input {
  padding: 16px;
  width: 100%;
  position: absolute;  // 改为绝对定位
  bottom: 45px;          // 固定在底部
  border-top: 1px solid #ebeef5;
  background: white;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
}
.message-list {
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 60px;
}

/* 修改滚动条的宽度 */
.message-list::-webkit-scrollbar {
  width: 10px; /* 滚动条的宽度 */
}

/* 修改滚动条的轨道（背景部分） */
.message-list::-webkit-scrollbar-track {
  background: #f1f1f1; /* 轨道的背景颜色 */
  border-radius: 10px; /* 轨道的圆角 */
}

/* 修改滚动条的滑块（可移动部分） */
.message-list::-webkit-scrollbar-thumb {
  background: #888; /* 滑块的背景颜色 */
  border-radius: 10px; /* 滑块的圆角 */
}

/* 当滑块悬停时的样式 */
.message-list::-webkit-scrollbar-thumb:hover {
  background: #555; /* 悬停时滑块的背景颜色 */
}
.message-item {
  margin: 10px 0;
  clear: both;

  &.left {
    float: left;
    .message-bubble {
      background: #f1f3fa;
    }
  }

  &.right {
    float: right;
    .message-bubble {
      background: #409eff;
      color: white;
    }
  }
}

.message-bubble {
  max-width: 300px;
  padding: 10px 15px;
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);

  .content {
    word-break: break-word;
  }

  .time {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
  }
}
</style>
